package wang.chunfan.code.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @version 1.0
 * @Author wangchunfan
 * @Date 2020/6/1 11:55
 **/
public class TimeClientHandle implements Runnable {
    private String host;
    private int port;
    private Selector selector;
    private SocketChannel socketChannel;
    private volatile boolean stop;


    /**
     * 初始化
     */
    public TimeClientHandle(String host, int port) {
        this.host = host;
        this.port = port;
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void run() {
        try {
            doConnect();
            while (!stop) {
                selector.select(1000);
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectedKeys.iterator();
                SelectionKey selectedKey = null;
                while (iterator.hasNext()) {
                    selectedKey = iterator.next();
                    iterator.remove();
                    try {
                        handleInput(selectedKey);
                    } catch (Exception e) {
                        if (selectedKey != null) {
                            selectedKey.cancel();
                            if (selectedKey.channel() != null) {
                                selectedKey.channel().close();
                            }
                        }
                    }
                }
            }

            if (selector != null) {
                try {
                    selector.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * 处理事件
     */
    private void handleInput(SelectionKey selectedKey) throws IOException {
        if (selectedKey.isValid()) {
            SocketChannel socketChannel = (SocketChannel) selectedKey.channel();
            if (selectedKey.isConnectable()) {
                if (socketChannel.finishConnect()) {
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    doWrite(socketChannel);
                } else {
                    // 连接失败，退出进程
                    System.exit(1);
                }
            }
            if (selectedKey.isReadable()) {
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int len = socketChannel.read(readBuffer);
                if (len > 0) {
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes, "UTF-8");
                    System.out.println("Now is: " + body);
                    stop();
                } else if (len < 0) {
                    // 关闭链路
                    selectedKey.cancel();
                    socketChannel.close();
                } else {
                    // 读到 0 字节，忽略
                }
            }
        }
    }

    /**
     * 创建链接
     */
    private void doConnect() throws IOException {
        if (socketChannel.connect(new InetSocketAddress(host, port))) {
            // 连接成功，注册读就绪事件
            socketChannel.register(selector, SelectionKey.OP_READ);
            doWrite(socketChannel);
        } else {
            // 未连接成功，注册连接就绪事件
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
        }
    }

    /**
     * 发送请求
     */
    private void doWrite(SocketChannel socketChannel) throws IOException {
        byte[] request = "QUERY TIME ORDER".getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(request.length);
        writeBuffer.put(request);
        writeBuffer.flip();
        while (writeBuffer.hasRemaining()) {
            socketChannel.write(writeBuffer);
        }
        System.out.println("Send order 2 server succeed.");
    }

    public void stop() {
        this.stop = true;
    }
}
